package com.wuliang.generate.common.core.filter;

import com.wuliang.generate.common.core.utils.JwtTokenUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求拦截，认证用户是否拥有权限访问此接口
 *
 * @author WuLiang
 */
public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

    /**
     * @param authenticationManager 认证管理器
     */
    public JwtAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 对请求进行过滤
     *
     * @param request  请求
     * @param response 响应
     * @param chain    过滤器
     * @throws IOException      读取请求时异常
     * @throws ServletException 请求响应异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws
                                                                                                                 IOException,
                                                                                                                 ServletException {

        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (hasToken(tokenHeader)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        /*SecurityContextHolder.getContext().setAuthentication(getAuthentication(request));*/
        super.doFilterInternal(request, response, chain);
    }

    /**
     * 这里从token中获取用户信息，然后声明一个SpringSecurity使用的令牌
     *
     * @param request 令牌
     * @return 对用户进行权限验证
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) throws RuntimeException {
//        JwtTokenUtils.refreshToken(token);
//        AuthenticationDetail authenticationDetail = (AuthenticationDetail) JsonUtils
//                .mapToObject(JwtTokenUtils.getAuthenticationDetail(request), AuthenticationDetail.class);
//        if (authenticationDetail != null) {
//            return new UsernamePasswordAuthenticationToken(authenticationDetail.getUsername(), authenticationDetail.getPassword(), authenticationDetail.getAuthorities());
//        }
        return null;
    }

    private boolean hasToken(String tokenHeader) {
        return tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX) ||
               tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "").trim().isEmpty();
    }

}
